<!--
* description: 采购管理-_网点
* author: zouzhu
* createdDate: 2021-01-22
-->
<template>
  <div class="app-container app-container-table">
    <one-table-template
      ref="multipleTable"
      :dynamic-buttons="tableButtons"
      :dynamic-components="tableComponents"
      :dynamic-api-config="dynamicApiConfigs"
      :dynamic-table-cols="tableCols"
      :dynamic-form-fields="formField"
      :dynamic-is-show-select="true"
      :dynamic-is-init-table="true"
      :dynamic-is-fix-choose="false"
      :dynamic-is-fix-index="false"
      :dynamic-is-show-more-btn="true"
      :callback-obj="callbackObj"
    />
    <part-order-add
      :key="editPopupsKey"
      :isViewPopWindows.sync="isViewAddWindows"
      :dynamic-edit-row-data="editRowData"
      :popups-state="editPopupsState"
      @close="close"
    />

    <calendar-popups :popups-visible.sync="popUpSwitch" />
  </div>
</template>

<script>
import { formMixins } from '@/components/mixins/formMixins'
import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
import OneTableTemplate from '@/components/templates/oneTable'
import api from '@/api/vehicleManagement'
import PartOrderAdd from './partOrderAdd.vue'
import { vehiclePdiPriceInquirys } from '@/api/se/vehiclePdiPriceInquiry'
import { exportExcel } from '@/utils/getTimeString.js'
import calendarPopups from '@/views/pa/purchasingManagement/partOrderBranchMake/calendarPopups'

export default {
  name: 'PartOrderBranchMake',
  components: {
    OneTableTemplate,
    PartOrderAdd,
    calendarPopups
  },
  mixins: [oneTableWithViewTemplateMixins, formMixins],
  data() {
    null
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path

    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])
    return {
      popUpSwitch: false,
      isViewAddWindows: false, // 是否显示新增弹窗
      dynamicApiConfigs: vehiclePdiPriceInquirys.queryPartOrderMakePage,
      // 动态生成网格列
      tableCols:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          : [
            {
              prop: 'controlBtn',
              label: '操作', // 操作
              codeField: 'controlBtn',
              width: 50,
              align: 'center',
              isComponent: true,
              comps: [
                {
                  compKey: 'propKey1',
                  labelName: '修改', // 编辑
                  align: 'center',
                  codeField: 'editControlBtn',
                  clickEvent: index => this.edit(index),
                  component: () => import('@/components/org/linkButton')
                }
              ]
            },
            {
              prop: 'purOrderCode',
              label: '订单号',
              align: 'center',
              width: 180
            },
            {
              prop: 'purOrderTypeCn',
              label: '订单类型',
              align: 'center'
            },
            {
              prop: 'purDate',
              label: '订货日期',
              align: 'center',
              width: 110
            },
            {
              prop: 'supplierShortName',
              label: '供应商信息',
              align: 'center'
            },
            {
              prop: 'orderVariety',
              label: '订货品种数',
              align: 'center'
            },
            {
              prop: 'purAmount',
              label: '订货金额',
              align: 'center'
            },
            // {
            //   prop: 'transportModeName',
            //   label: '运输方式',
            //   align: 'center'
            // },
            {
              prop: 'orderStatusCn',
              label: '审核状态',
              align: 'center'
            },
            {
              prop: 'createdDate',
              label: '制单时间',
              align: 'center'
            },
            {
              prop: 'creator',
              label: '制单人',
              align: 'center'
            },
            {
              prop: 'dlrAuditDate',
              label: '网点审核时间',
              align: 'center'
            },
            {
              prop: 'dlrAuditor',
              label: '网点审核人',
              align: 'center'
            },
            // {
            //   prop: 'oemAuditDate',
            //   label: '总部审核时间',
            //   align: 'center'
            // },
            // {
            //   prop: 'oemAuditor',
            //   label: '总部审核人',
            //   align: 'center'
            // },
            {
              prop: 'rejectReason',
              label: '驳回原因',
              align: 'center'
            },
            {
              prop: 'remark',
              label: '备注',
              align: 'center'
            }
          ],
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
            .tableComponents
          : [
            // 库存状态
            {
              compKey: 'compKey1',
              labelName: '订单号：',
              codeField: 'purOrderCode',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true,
              span: 6
            },
            // 车辆状态
            {
              compKey: 'compKey2',
              labelName: '订货日期：',
              codeField: 'startDate,endDate',
              component: () =>
                import('@/components/org/datePicker/andtDatePicker'),
              type: 'YYYY-MM-DD',
              // dataToObject: { timer: true, thirtyTime: true, hhmmss: true },
              format: 'yyyy-MM-dd',
              isMust: true,
              span: 6
            },
            {
              compKey: 'compKey3',
              labelName: '订单类型：',
              codeField: 'purOrderType',
              component: () => import('@/components/org/commonSelect'),
              customObj: {
                api: vehiclePdiPriceInquirys.queryOrderType
              },
              type: 'dropdownList',
              isMul: false,
              isMust: true
            },
            // 审核状态
            {
              compKey: 'compKey4',
              labelName: '供应商：',
              codeField: 'supplierId',//主页面显示
              textField: 'supplierShortName',
              component: () => import('@/views/ve/planReport/components/multipleSearchInput'),
              isMust: true,
              dataToObject: {
                // 控制弹窗页面 搜索 网格 元素
                oFields: 'supplierId,supplierShortName',//主页面传递和显示
                tableComponents: [
                  {
                    compKey: 'compKey1',
                    labelName: '供应商编码：',
                    codeField: 'supplierCode',
                    component: () => import('@/components/org/commonInput'),
                    type: 'inputText',
                    isMust: true,
                    span: 8
                  },
                  {
                    compKey: 'compKey2',
                    labelName: '供应商名称：',
                    codeField: 'supplierShortName',
                    component: () => import('@/components/org/commonInput'),
                    type: 'inputText',
                    isMust: true,
                    span: 8
                  }
                ],
                tableCols: [
                  {
                    prop: 'supplierCode',
                    label: '供应商编码'
                  },
                  {
                    prop: 'supplierShortName',
                    label: '供应商名称'
                  }
                ],
                formField: {
                  supplierId:'',
                  supplierCode: '',
                  supplierShortName: ''
                },
                returnField: {
                  prop: 'supplierId',
                  label: '供应商编码'
                },
                api: vehiclePdiPriceInquirys.queryPartSources
              },
              span: 6
            },
            // VIN码
            // {
            //   compKey: "compKey5",
            //   labelName: "订单状态：",
            //   codeField: "orderStatusCn",
            //   component: () => import("@/components/org/commonSelect"),
            //   customObj: {
            //     api: vehiclePdiPriceInquirys.queryOrderStatus,
            //   },
            //   type: "dropdownList",
            //   isMul: false,
            //   isMust: false,
            // },
            // 质量状态
            // {
            //   compKey: 'compKey6',
            //   labelName: '运输方式：',
            //   codeField: 'transportModeCode',
            //   component: () => import('@/components/org/commonSelect'),
            //   customObj: {
            //     api: vehiclePdiPriceInquirys.queryPartTransports
            //   },
            //   oFields: 'transportModeCode,transportModeName',
            //   type: 'dropdownList',
            //   isMul: false,
            //   isMust: false
            // }
            // 审核状态
            // {
            //   compKey: "compKey7",
            //   labelName: "只限本人",
            //   codeField: "aaa",
            //   lookuptype: "VE0212",
            //   component: () => import("@/components/org/checkBox"),
            //   type: "inputText",
            //   isMust: false,
            //   span: 6,
            // },
          ],
      tableButtons: [
        {
          compKey: 'btnKey1021',
          type: '',
          size: 'small',
          name: 'chakan',
          clickEvent: () => {
            this.popUpSwitch = true
          },
          text: '订货日历',
          position: 'left'
        },
        {
          conmpKey: 'btenKey1',
          type: 'primary',
          size: 'small',
          name: 'search',
          text: '查询',
          clickEvent: () => this.queryTable(1),
          position: 'right'
        },
        {
          conmpKey: 'btenKey2',
          type: 'primary',
          size: 'small',
          clickEvent: () => this.add(),
          text: this.$t('sys.button.add'),
          icon: 'el-icon-circle-plus-outline',
          position: 'left' // 新增
        },
        {
          conmpKey: 'btenKey3',
          type: '',
          size: 'small',
          clickEvent: () => this.submit(),
          text: this.$t('sys.button.submit'),
          icon: 'el-icon-circle-check',
          position: 'left' // 提交
        },
        {
          conmpKey: 'btenKey4',
          type: '',
          size: 'small',
          text: '作废',
          icon: 'el-icon-delete',
          clickEvent: () => this.cancellation(),
          position: 'left'
        },
        {
          conmpKey: 'btenKey5',
          type: '',
          size: 'small',
          clickEvent: () => this.exportExcel111(),
          text: this.$t('sys.button.export'),
          name: 'export',
          position: 'right' // 导出
        },
        {
          conmpKey: 'btenKey6',
          type: '',
          size: 'small',
          text: '重置',
          name: 'reset',
          clickEvent: () => {
            for (const attr in this.formField) {
              this.formField[attr] = ''
            }
            this.tableComponents.find(o => o.codeField.indexOf(',') > -1).compKey = this.$utils.generateId()
          },
          position: 'right'
        }
      ],

      // 表单数据（无需赋值，由混入对象赋值）
      formField: this.$utils.getFormField(
        this,
        {
          'startDate,endDate':'',
          purOrderCode: '', // 订单号
          startDate: '', // 订货日期
          endDate: '',
          purOrderType: '', // 订单类型
          supplierId: '', // 供应商Id
          //supplierShortName: '', // 供应商简称
          orderStatusCn: '', // 订单状态
          // transportModeCode: '' // 运输方式
        },
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode]
      ),
      // 回调方法对象
      callbackObj: {
        // 网格点击回调事件
        // onRowClick: currentRow => {
        //   this.onRightRowClick(currentRow)
        // },
        // // 手动勾选网格时，拿到勾选网格的数据
        // onCheckSelect: (selection, row) => {
        //   this.selectiondata = selection
        // },
        onCheckSelectChange: selection => {
          // this.onCheckSelectChange1(selection)
          this.selectiondata = selection
        }
      }
    }
  },

  mounted() {
    // 查询有无订货日历
    this.queryCalendar()
  },

  methods: {
    async queryCalendar() {
      const apiUrl = 'mp/e3sh/spareparts/mallorder/partOrderMakeDlrService/queryCalendar.do'
      const variables = {}
      let response
      try {
        response = await this.$requestAPI({ apiUrl, variables })
      } catch (e) { return }
      if (response.result === '1') {
      } else {
        const msg = await this.$alert(response.msg, '提示')
        // if (msg === 'confirm') {
        //   // 跳转
        //   this.$router.push('/partsModule/procuremenManagers/orderCalendarSetting')
        // }
      }
    },
    /**
     * @description 关闭弹窗
     * @time 2020/01/22
     */
    close() {
      this.isViewAddWindows = false
      this.queryTable(1)
    },
    add(index) {
      this.editPopupsState = 'add'
      this.isViewAddWindows = true
    },
    edit(index) {
      this.editPopupsState = 'edit'
      this.isViewAddWindows = true
      // this.editRowData = this.$refs["multipleTable"].list[index];
      this.editRowData = this.$utils.deepCopy(
        this.$refs['multipleTable'].list[index]
      )
      // console.log(this.editRowData)
    },
    // 提交
    submit() {
      if (!this.selectiondata || this.selectiondata.length == 0) {
        this.$message({
          message: '请至少选择一条数据',
          type: 'warn',
          uration: 1000
        })
      } else {
        const queryObj = {
          // 保存mutation
          type: 'mutation',
          // api配置
          apiConfig: vehiclePdiPriceInquirys.updateOrderStatusSubmit,
          // 条件/实体参数（变量），根据typeParam中的定义配置
          variables: { list: this.selectiondata }
        }
        // 转换了中台请求格式数据
        var paramD = this.$getParams(queryObj)
        // 调用中台API方法（可复用）
        this.$requestAPI(paramD).then(response => {
          if (response.result === '1') {
            this.$message({
              message: '提交成功',
              type: 'success',
              duration: 2000
            })
            this.queryTable(1)
            this.selectiondata = []
          } else {
            // 保存失败
            this.$message({
              message: '提交失败',
              type: 'warn',
              uration: 2000
            })
          }
        })
      }
    },
    // 作废
    cancellation() {
      if (!this.selectiondata || this.selectiondata.length == 0) {
        this.$message({
          message: '请至少选择一条数据',
          type: 'warn',
          uration: 1000
        })
      } else {
        const queryObj = {
          // 保存mutation
          type: 'mutation',
          // api配置
          apiConfig: vehiclePdiPriceInquirys.updateOrderStatusInvalid,
          // 条件/实体参数（变量），根据typeParam中的定义配置
          variables: { list: this.selectiondata }
        }
        // 转换了中台请求格式数据
        var paramD = this.$getParams(queryObj)
        // 调用中台API方法（可复用）
        this.$requestAPI(paramD).then(response => {
          if (response.result === '1') {
            this.$message({message: '作废成功', type: 'success', duration: 2000})
            this.selectiondata = []
            this.queryTable(1)
          } else {
            // 保存失败
            this.$message({
              message: '作废失败',
              type: 'warn',
              duration: 2000
            })
          }
        })
      }
    },
    // 导出
    exportExcel111() {
      exportExcel(
        this.formField,
        vehiclePdiPriceInquirys.exportPartOrderMakeDlr.APIUrl,
        vehiclePdiPriceInquirys.exportPartOrderMakeDlr.ServiceCode,
        '备件订单制作_网点'
      )
    }
  }
}
</script>

<style>
</style>
